package com.lin.fengxiu.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lin.fengxiu.exception.http.ServerErrorException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName MapAndJson
 * @Description AttributeConverter泛型有两个泛型参数，第一个类型Map<String,Object>是当前字段的数据类型，第二个类型 String 是当前字段在数据库的数据类型。
 * @Author wushaopei
 * @Date 2021/3/14 22:43
 * @Version 1.0
 */
@Converter
public class MapAndJson implements AttributeConverter<Map<String,Object>,String> {

    @Autowired
    private ObjectMapper mapper;

    /**
     * @Description 把模型字段转换为数据库字段
     * @param stringObjectMap
     * @return
     */
    @Override
    public String convertToDatabaseColumn(Map<String, Object> stringObjectMap) {
        try {
            return mapper.writeValueAsString(stringObjectMap);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new ServerErrorException(9999);
        }
    }

    /**
     * @Description 把数据库字段转换为实体字段
     * @param
     * @return
     */
    @Override
    public Map<String, Object> convertToEntityAttribute(String s) {
        try {
            return mapper.readValue(s, HashMap.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new ServerErrorException(9999);
        }
    }
}
